<template>
  <div class="all">
  <el-form
      ref="ruleFormRef"
      class="centered-form"
      style="max-width: 600px"
      :model="ruleForm"
      status-icon
      :rules="rules"
      label-width="auto"
  >
    <el-form-item label="账号" prop="empName">
      <el-input v-model="ruleForm.empName"/>
    </el-form-item>
    <el-form-item label="密码" prop="empPassword">
      <el-input v-model="ruleForm.empPassword" type="password" autocomplete="off"/>
    </el-form-item>
    <el-button type="primary" @click="submitForm()">登录</el-button>
  </el-form></div>
</template>

<script lang="ts" setup>
import { reactive, ref } from 'vue'
import { ElMessage, FormInstance, FormRules } from 'element-plus'
import axios from 'axios'
import router from '../router'

const ruleFormRef = ref<FormInstance | null>(null)

const validateEmpName = (rule: any, value: string, callback: (error?: Error) => void) => {
  if (!value) {
    return callback(new Error('账号不能为空！'))
  }
  callback()
}

const validateEmpPassword = (rule: any, value: string, callback: (error?: Error) => void) => {
  if (!value) {
    return callback(new Error('密码不能为空！'))
  }
  callback()
}

const ruleForm = reactive({
  empName: '',
  empPassword: '',
})

const rules: FormRules<typeof ruleForm> = reactive({
  empName: [{ validator: validateEmpName, trigger: 'blur' }],
  empPassword: [{ validator: validateEmpPassword, trigger: 'blur' }],
})

function getJwtToken(): string | null {
  return localStorage.getItem('jwtToken')
}

function parseJwt(token: string): Record<string, any> | null {
  try {
    const base64Url = token.split('.')[1];
    const base64 = base64Url.replace(/-/g, '+').replace(/_/g, '/');
    const jsonPayload = atob(base64);
    // 使用 TextDecoder 将 ISO-8859-1 转换为 UTF-8
    const decoder = new TextDecoder('utf-8');
    const utf8String = decoder.decode(new Uint8Array([...jsonPayload.split('').map(char => char.charCodeAt(0))]));
    return JSON.parse(utf8String);
  } catch (error) {
    console.error('Failed to parse JWT token:', error);
    return null;
  }
}

const submitForm = async () => {
  await ruleFormRef.value?.validate(async (valid) => {
    if (valid) {
      try {
        const res = await axios.post('/login', ruleForm)
        const token = res.data.data // 根据实际响应结构进行调整
        if (token) {
          localStorage.setItem('jwtToken', token)
          const storedToken = getJwtToken()
          if (storedToken) {
            const decoded = parseJwt(storedToken)
            console.log(decoded)
            if (decoded && decoded.name) {
              console.log('用户名:', decoded.name)
              const name = decoded.name
              localStorage.setItem('userName', name); // 存储用户名
            } else {
              console.log('Failed to decode JWT token or name not found')
            }
          } else {
            console.log('JWT token not found in localStorage')
          }
          ElMessage({ message: '登录成功！', type: 'success' })
          router.replace('/index')
        } else {
          ElMessage({ message: '登录失败！账号或密码错误！', type: 'error' })
          console.error('No token returned from server')
        }
      } catch (e) {
        ElMessage({ message: '登录失败！账号或密码错误！', type: 'error' })
        console.error('Login request failed:', e)
      }
    } else {
      console.log('表单验证失败！')
    }
  })
}
</script>
<style>
.all {
  position: relative; /* 设置为相对定位，以便子元素可以使用绝对定位 */
  height: 100vh;
  width: 100%;
  background: url("src/assets/loginindex.jpeg") no-repeat center center; /* 使用@别名引用assets目录，并设置图片不重复、居中 */
  background-size: cover; /* 让图片覆盖整个容器 */
  overflow: hidden; /* 防止内容溢出 */
}

.centered-form {
  position: absolute; /* 设置为绝对定位 */
  bottom: 220px; /* 距离页面底部20px */
  left: 30%; /* 水平方向居中，先偏移50% */
  transform: translateX(-50%); /* 使用transform属性将元素向左移动自身宽度的50%，实现真正居中 */
  display: flex;
  flex-direction: column;
  align-items: center;
  width: 500px; /* 设置表单宽度 */
  padding: 20px;
  height: 200px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.5);
  border-radius: 8px;
  background-color: rgba(185, 183, 183, 0.8); /* 设置半透明的背景色，以便能看到背景图片 */
}

.centered-form .el-form-item {
  margin-bottom: 20px; /* 增加表单项之间的间距 */
}

.centered-form .el-button {
  width: 300px; /* 使按钮宽度与表单宽度一致 */
}

.centered-form .el-input__inner {
  border-radius: 4px; /* 添加圆角 */
  border: 1px solid #dcdcdc; /* 设置边框颜色 */
  padding: 10px; /* 增加内边距 */
  box-sizing: border-box; /* 确保内边距不会增加元素的总宽度 */
}
</style>